/**
 *  费用模块重写
 *  ExpenseAdjunct :: (<Invoice | Attachment | Business +  Util + ExpenseAdjunctDetail>  | <ExpenseAdjunctList>) | <Nothing>
 *  费用附属 ::（ <发票 | 附件 | 商务卡 + 工具栏 +  附属主体信息> | 附属列表） | 没有任何图片
 */
import React, { Component } from 'react';
import Nothing from './nothing';
import 'styles/expense/expense-adjunct.scss';
import ExpenseAdjunctRead from './expense-adjunct-read';
import ExpenseAdjunctList from './expense-adjunct-new-list';
import ExpenseAdjunctService from './expense-adjunct-service';
import AuditTipsButton from '../../financial-management/new-finance-audit/components/audit-tips';
import ExpenseService from '../expense-service';
import { getAttachment }  from 'containers/expense/util';

class ExpenseAdjunct extends Component {

  static contextTypes = {
    annotates: React.PropTypes.array,
    currentExpense: React.PropTypes.object,
    mergeAdjuncts: React.PropTypes.array
  };

  constructor(props, context) {
    super(props, context);
    this.state = {
      labelFilter: [], // 发票标签筛选
      receiptChanges: {}, // 发票改动
      receiptLabelsDesc: {}, // 发票标签说明
      currentAttachmentIndex: 0,
      currentFlag: '',
      currentAttachment: {},
      currentAdjunct: {},
      attachmentChecklist: {},
      init: true,
      isListMode: window.localStorage.getItem('expense-adjunct-mode') ? window.localStorage.getItem('expense-adjunct-mode') === 'true' : true,
      annotates: context.annotates,
      isEditing: false,
      ...this.init(context)

    };
  }

  componentWillReceiveProps(nextProps, nextContext) {
    nextProps.randomHash !== this.props.randomHash && (this.setState({ ...this.init(nextContext) }), this.handleReceiptChange(nextContext.currentExpense));
  }

  componentDidMount() {
    this.setState({ ...this.init(this.context) });
    this.handleReceiptChange(this.context.currentExpense);
  }

  init = (context) => {
    const { mergeAdjuncts = [], currentExpense: { receiptList = [] } } = context;
    const state = this.state || {};
    const receiptLabels = [];
    let { currentFlag = '', currentAdjunct = {}, currentAttachment = {}, attachmentChecklist = {}, currentAttachmentIndex = 0, init = true } = state;
    receiptList.forEach(item => {
      item.receiptLabels.forEach(label => {
        !receiptLabels.some(item => item.type === label.type) && receiptLabels.push(label);
      });
    });

    mergeAdjuncts.forEach((adjunct, index) => {
      if (index === 0 && init) {
        currentFlag = adjunct.type;
        currentAdjunct = adjunct.body[0];
        currentAttachment = getAttachment(currentAdjunct);
        currentAttachmentIndex = 0;
      }

      if (!init && currentFlag === adjunct.type) {
        currentAdjunct = adjunct.body[currentAttachmentIndex];
        currentAttachment = getAttachment(currentAdjunct);
      }
      adjunct.body.forEach(item => {
        const _attachment = getAttachment(item);
        attachmentChecklist[(_attachment || item).id] = _attachment.checked;
      });
    });

    return {
      currentFlag,
      mergeAdjuncts,
      receiptLabels,
      currentAdjunct,
      currentAttachment,
      attachmentChecklist,
      currentAttachmentIndex
    };
  };

  handleReceiptChange = async (currentExpense) => {
    ExpenseAdjunctService.initReceiptChangeData(currentExpense, this);
  };

  handleModeChange = (isListMode) => {
    window.localStorage.setItem('expense-adjunct-mode', isListMode);
    this.setState({ isListMode });
  };

  handleJumpRead = (currentAdjunct, currentFlag, isEditing) => {
    const { mergeAdjuncts } = this.state;
    let currentAttachmentIndex = mergeAdjuncts.filter(item => item.type === currentFlag)[0].body.findIndex(item => item.id === currentAdjunct.id);
    this.setState({
      currentAdjunct,
      currentFlag,
      currentAttachmentIndex,
      isEditing: !!isEditing,
      currentAttachment: getAttachment(currentAdjunct)
    });
    this.handleModeChange(false);
  };

  handleChangeAttachment = (flag) => {
    this.refs.read && this.refs.read.handleChangeAttachment()(flag);
  };

  handleAttachmentChecklist = (id, checked) => {
    const { attachmentChecklist } = this.state;
    attachmentChecklist[id] = checked;
    this.setState({ attachmentChecklist });
  };

  onInvoiceChange = (invoice, type, reviewResult) => {
    this.setState({ init: type === 'DELETE' }, () => this.props.onInvoiceChange(invoice, type, reviewResult));
  };

  handleAnnotate = async () => {
    const { currentExpense: { invoiceOID } } = this.context;
    const annotates = await ExpenseService.getAnnotate(invoiceOID);
    this.setState({ annotates });
  };

  render() {
    const {
      mergeAdjuncts, isListMode, currentAttachment, currentFlag, currentAdjunct, receiptLabels,
      currentAttachmentIndex, receiptLabelsDesc, receiptChanges, attachmentChecklist, annotates, isEditing
    } = this.state;
    const { leftWidth, randomHash } = this.props;
    return (
      <article className='expense-adjunct'>
        <AuditTipsButton
          from="expenseDetail"
          pageKey="expenseDetail"
          radioKey="expenseDetail_image"
          lampStyle={{ top: 50, zIndex: 2 }}
        />
        <ExpenseAdjunctRead
          ref={'read'}
          annotates={annotates}
          isListMode={isListMode}
          currentFlag={currentFlag}
          randomHash={randomHash}
          mergeAdjuncts={mergeAdjuncts}
          receiptLabels={receiptLabels}
          receiptChanges={receiptChanges}
          currentAdjunct={currentAdjunct}
          refreshAnnotate={this.handleAnnotate}
          receiptLabelsDesc={receiptLabelsDesc}
          currentAttachment={currentAttachment}
          isShow={mergeAdjuncts[0] && !isListMode}
          handleModeChange={this.handleModeChange}
          attachmentChecklist={attachmentChecklist}
          currentAttachmentIndex={currentAttachmentIndex}
          onInvoiceChange={this.onInvoiceChange}
          isEditing={isEditing}
          handleAttachmentChecklist={this.handleAttachmentChecklist}
        />
        <ExpenseAdjunctList
          annotates={annotates}
          leftWidth={leftWidth}
          randomHash={randomHash}
          mergeAdjuncts={mergeAdjuncts}
          receiptLabels={receiptLabels}
          currentAdjunct={currentAdjunct}
          receiptChanges={receiptChanges}
          refreshAnnotate={this.handleAnnotate}
          changeMode={this.handleModeChange}
          handleJumpRead={this.handleJumpRead}
          receiptLabelsDesc={receiptLabelsDesc}
          onInvoiceChange={this.onInvoiceChange}
          isShow={mergeAdjuncts[0] && isListMode}
        />
        <Nothing isShow={!mergeAdjuncts[0]}/>
      </article>
    );
  }
}

ExpenseAdjunct.propTypes = {};

export default ExpenseAdjunct;
